package com.systec.smalltools.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.systec.smalltools.entity.ExportInfo;
import com.systec.smalltools.entity.ImportInfo;
import com.systec.smalltools.service.EasyService;
import com.systec.smalltools.util.ResultVOUtils;
import com.systec.smalltools.vo.ResultVO;
import com.systec.smalltools.vo.ReturnResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;


/**
 * @author cmd
 */
@Controller
@RequestMapping("/gadget")
public class GadgetController {
    @Autowired
    private EasyService easyService;


    /**
     * 进入运维小工具首页
     *
     * @return 运维小工具首页
     */
    @GetMapping("/index")
    public String index() {
        return "index";
    }


    /**
     * 跳转到运维小工具--并发数据统计页面
     *
     * @return 并发数据统计页面
     */
    @GetMapping("/toCount")
    public String toCount() {
        return "count";
    }


    /**
     * 上传文件进行统计
     *
     * @param file          前端的excel文件
     * @param intervalTime  并发间隔
     * @param skipFirstLine 是否跳过首行
     * @return
     */
    @ResponseBody
    @RequestMapping("/uploadToFile")
    public ResultVO<ReturnResultVO> upload(@RequestParam("file") MultipartFile file,
                                           @RequestParam("intervalTime") Integer intervalTime,
                                           @RequestParam("skipFirstLine") boolean skipFirstLine) {

        ReturnResultVO returnResultVO = new ReturnResultVO();
        List<ImportInfo> importInfoList;
        //解析文件出现异常，直接返回页面
        try {
            importInfoList = easyService.getAllImportInfos(file, skipFirstLine).getImportInfoList();
            returnResultVO.setProblemLines(easyService.getAllImportInfos(file, skipFirstLine).getProblemLines());
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVOUtils.error("文件解析异常！", returnResultVO);
        }
        //解析结果
        returnResultVO.setExportInfoList(easyService.getExportInfos(intervalTime, easyService.getEveryDayImportInfo(importInfoList)));
        //正确解析的数据为空时，返回结果为空，returnResultVO对象带着脏数据位置
        if (returnResultVO.getExportInfoList() == null || returnResultVO.getExportInfoList().isEmpty()) {
            return ResultVOUtils.error("可以解析的内容为空，请检查格式或者内容！", returnResultVO);
        }
        //返回正确的解析结果，并携带脏数据相关的信息
        return ResultVOUtils.success(returnResultVO);
    }


    /**
     * 导出统计数据的excel文件
     *
     * @param file                前端的excel文件
     * @param intervalTime        前端的excel文件
     * @param skipFirstLine       是否跳过首行
     * @param httpServletResponse
     * @return
     * @throws IOException
     */
    @PostMapping("/exportExcel")
    public String exportExcel(MultipartFile file, Integer intervalTime, boolean skipFirstLine, HttpServletResponse httpServletResponse) {
        List<ImportInfo> importInfoList = null;
        List<List<ImportInfo>> list = null;

        try {
            importInfoList = easyService.getAllImportInfos(file, skipFirstLine).getImportInfoList();
        } catch (Exception e) {
            e.printStackTrace();
            //出现解析异常，重定向到统计页面
            return "redirect:/gadget/toCount";
        }

        list = easyService.getEveryDayImportInfo(importInfoList);

        List<ExportInfo> exportInfoList = new ArrayList<>();
        exportInfoList = easyService.getExportInfos(intervalTime, list);
        if (exportInfoList == null || exportInfoList.isEmpty()) {

            //出现解析结果为空，重定向到统计页面
            return "redirect:/gadget/toCount";
        }
        httpServletResponse.setContentType("application/vnd.ms-excel");

        //防止中文乱码
        httpServletResponse.setCharacterEncoding("utf-8");
        String fileName = null;
        try {
            fileName = URLEncoder.encode("统计结果：并发间隔为" + intervalTime + "分钟" + file.getOriginalFilename(), "utf-8");
        } catch (UnsupportedEncodingException e) {

            e.printStackTrace();
            //出现解析结果为空，重定向到统计页面
            return "redirect:/gadget/toCount";
        }
        httpServletResponse.setHeader("Content-disposition", "attachment;filename=" + fileName);
        try {
            EasyExcel.write(httpServletResponse.getOutputStream(), ExportInfo.class)
                    .sheet("sheet0")
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    .doWrite(exportInfoList);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


}
